﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;

namespace ResourceEnumerator.Inrastructure
{
    public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName)
        {
            var temp = PropertyChanged;

            temp?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected void RaisePropertyChanged(params string[] propetyNames)
        {
            if (propetyNames == null) return;

            foreach (var propetyName in propetyNames)
            {
                RaisePropertyChanged(propetyName);
            }
        }

        protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
        {
            if (propertyExpression == null) throw new ArgumentNullException(nameof(propertyExpression));

            var memberExpression = propertyExpression.Body as MemberExpression;
            if (memberExpression == null)
                throw new ArgumentException("invalid member expression", nameof(propertyExpression));

            var propertyInfo = memberExpression.Member as PropertyInfo;
            if (propertyInfo == null)
                throw new ArgumentException("invalid property expression", nameof(propertyExpression));

            if (propertyInfo.GetGetMethod().IsStatic)
                throw new ArgumentException("static properties are not supported", nameof(propertyExpression));

            RaisePropertyChanged(memberExpression.Member.Name);
        }

        #endregion
    }
}
